/*
 * Wazuh Vulnerability scanner - Scan Orchestrator
 * Copyright (C) 2015, Wazuh Inc.
 * Jun 1, 2023.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#ifndef _RESULT_INDEXER_HPP
#define _RESULT_INDEXER_HPP

#include "chainOfResponsability.hpp"
#include "indexerConnector.hpp"
#include "scanContext.hpp"

/**
 * @brief ResultIndexer class.
 *
 * @tparam TIndexerConnector indexer connector type.
 * @tparam TScanContext scan context type.
 */
template<typename TIndexerConnector = IndexerConnector, typename TScanContext = ScanContext>
class TResultIndexer final : public AbstractHandler<std::shared_ptr<TScanContext>>
{
private:
    std::shared_ptr<TIndexerConnector> m_indexerConnector;

public:
    // LCOV_EXCL_START
    /**
     * @brief ResultIndexer constructor.
     *
     * @param indexerConnector Indexer connector.
     */
    explicit TResultIndexer(std::shared_ptr<TIndexerConnector> indexerConnector)
        : m_indexerConnector(std::move(indexerConnector))
    {
    }
    // LCOV_EXCL_STOP

    /**
     * @brief Handles request and passes control to the next step of the chain.
     *
     * @param data Scan context.
     * @return std::shared_ptr<TScanContext> Abstract handler.
     */
    std::shared_ptr<TScanContext> handleRequest(std::shared_ptr<TScanContext> data) override
    {
        if (m_indexerConnector != nullptr)
        {
            for (const auto& [key, value] : data->m_elements)
            {
                logDebug2(WM_VULNSCAN_LOGTAG, "Processing and publish key: %s", key.c_str());
                if (value.contains("operation") && value.contains("id"))
                {
                    m_indexerConnector->publish(value.dump());
                }
                else
                {
                    logError(WM_VULNSCAN_LOGTAG, "Invalid element to publish: %s", value.dump().c_str());
                }
            }
        }
        return AbstractHandler<std::shared_ptr<TScanContext>>::handleRequest(std::move(data));
    }
};

using ResultIndexer = TResultIndexer<>;

#endif // _RESULT_INDEXER_HPP
